package cn.melonlib.apis.support.model.view;

import cn.hutool.core.bean.BeanUtil;
import cn.melonlib.apis.support.model.entity.ApiRequestRecord;
import cn.melonlib.apis.support.model.entity.ApiRequestRecordIndex;
import cn.melonlib.cores.model.anno.ModelComment;
import cn.melonlib.objects.maps.JsonMap;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.EqualsAndHashCode;
import org.hibernate.annotations.Type;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.Lob;
import java.util.List;
import java.util.Map;

@Data
@EqualsAndHashCode(callSuper = true)
@ModelComment("接口访问日志")
public class ApiRequestRecordView extends ApiRequestRecordIndex {

    public ApiRequestRecordView(ApiRequestRecord requestRecord, ObjectMapper objectMapper) {
        BeanUtil.copyProperties(requestRecord,this,"variables","requestHeader","response");
        try{
            variables=objectMapper.readValue(requestRecord.getVariables(), new TypeReference<Map<String, Object>>() {
            });
        }catch (Exception e){
            variables=JsonMap.createMap().append("error",requestRecord.getVariables());
        }
        try{
            requestHeader=objectMapper.readValue(requestRecord.getRequestHeader(), new TypeReference<Map<String, Object>>() {
            });
        }catch (Exception e){
            requestHeader= JsonMap.createMap().append("error",requestRecord.getRequestHeader());
        }
        try{
            if(requestRecord.getResponse().startsWith("[")){
                response=objectMapper.readValue(requestRecord.getResponse(), new TypeReference<List<Map<String,Object>>>() {
                });
            }else{
                response=objectMapper.readValue(requestRecord.getResponse(), new TypeReference<Map<String,Object>>() {
                });
            }
        }catch (Exception e){
            response=requestRecord.getResponse();
        }
    }

    @ModelComment("操作语句")
    private String statement;

    @ModelComment("参数")
    @Column
    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Type(type = "org.hibernate.type.TextType")
    private Map<String,Object> variables;

    @ModelComment("请求头")
    @Column
    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Type(type = "org.hibernate.type.TextType")
    private Map<String,Object> requestHeader;

    @ModelComment("响应数据")
    @Column
    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Type(type = "org.hibernate.type.TextType")
    private Object response;
}
